package com.bnyy.medicalHousekeeper.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.bnyy.medicalHousekeeper.DialogHelper;
import com.bnyy.medicalHousekeeper.R;
import com.bnyy.medicalHousekeeper.adapter.GoodsAdapter;
import com.bnyy.medicalHousekeeper.base.BaseActivityImpl;
import com.bnyy.medicalHousekeeper.bean.Goods;
import com.bnyy.medicalHousekeeper.bean.IndexData;
import com.bnyy.medicalHousekeeper.constants.GoodsEditType;
import com.bnyy.medicalHousekeeper.fragment.GoodsFragment;
import com.bnyy.medicalHousekeeper.request.BaseObserverImpl;
import com.bnyy.medicalHousekeeper.request.RequestManager;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.function.BiConsumer;
import java.util.function.Consumer;

import butterknife.BindView;

/**
 * Author : 关炳鹏
 * Description :
 * Date : 2023/2/6
 **/
public class GoodsActivity extends BaseActivityImpl implements GoodsAdapter.OnCheckedChangeListener {
    @BindView(R.id.tab_layout)
    TabLayout tabLayout;
    @BindView(R.id.view_pager)
    ViewPager2 viewPager;
    @BindView(R.id.tv_select_count)
    TextView tvSelectCount;
    @BindView(R.id.tv_confim)
    TextView tvConfim;
    @BindView(R.id.ll_select)
    LinearLayout llSelect;
    @BindView(R.id.et_search)
    EditText etSearch;
    @BindView(R.id.iv_delete)
    ImageView ivDelete;
    @BindView(R.id.ll_search)
    LinearLayout llSearch;

    private IndexData.Data.Type type;

    private ArrayList<Consumer<GoodsEditType>> consumers = new ArrayList<>();
    /**
     * 当前状态
     */
    private GoodsEditType goodsEditType = GoodsEditType.NORMAL;
    private HashMap<Integer, Goods> selectedGoodsMap = new HashMap<>();

    @Override
    public int getLayoutId() {
        return R.layout.activity_goods;
    }

    @Override
    public String getTitleStr() {
        return "";
    }

    @Override
    public boolean unuseRefreshLayout() {
        return true;
    }

    public static void show(Context context, IndexData.Data.Type type) {
        Intent intent = new Intent(context, GoodsActivity.class);
        intent.putExtra("type", type);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        type = (IndexData.Data.Type) getIntent().getSerializableExtra("type");

        if (type != null) {
//            if (type.getType() == 2) {
//                setManageOptions();
//            }
            setTitleStr(type.getTag_name());
            switch (type.getType()) {
                case 2:
                    llSearch.setVisibility(View.VISIBLE);
                    setManageOptions();
                    break;
            }
        }

        viewPager.setAdapter(new FragmentStateAdapter(getSupportFragmentManager(), getLifecycle()) {
            @NonNull
            @Override
            public Fragment createFragment(int position) {
                return GoodsFragment.getInstance(type, position + 1, goodsEditType);
            }

            @Override
            public int getItemCount() {
                return 2;
            }
        });
        new TabLayoutMediator(tabLayout, viewPager, new TabLayoutMediator.TabConfigurationStrategy() {
            @Override
            public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                switch (position) {
                    case 0:
                        tab.setText("普通商品");
                        break;
                    case 1:
                        tab.setText("服务商品");
                        break;
                }
            }
        }).attach();

        ivDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etSearch.setText("");
            }
        });

        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(s)) {
                    ivDelete.setVisibility(View.INVISIBLE);

                    getSupportFragmentManager().getFragments().forEach(new Consumer<Fragment>() {
                        @Override
                        public void accept(Fragment fragment) {
                            if (fragment instanceof GoodsFragment) {
                                ((GoodsFragment) fragment).setKeyword("");
                            }
                        }
                    });
                } else {
                    ivDelete.setVisibility(View.VISIBLE);
                }
            }
        });

        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if (i == EditorInfo.IME_ACTION_SEARCH) {
                    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (inputMethodManager != null) {
                        inputMethodManager.hideSoftInputFromWindow(etSearch.getWindowToken(), 0);
                    }

                    if (TextUtils.isEmpty(etSearch.getText())) {
                        Toast.makeText(mContext, "请输入关键字", Toast.LENGTH_SHORT).show();
                    } else {
                        String keyword = etSearch.getText().toString();
                        getSupportFragmentManager().getFragments().forEach(new Consumer<Fragment>() {
                            @Override
                            public void accept(Fragment fragment) {
                                if (fragment instanceof GoodsFragment) {
                                    ((GoodsFragment) fragment).setKeyword(keyword);
                                }
                            }
                        });
                    }
                }
                return false;
            }
        });

        tvConfim.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (selectedGoodsMap.size() > 0) {
                    DialogHelper.showNormalDialog(mContext, goodsEditType == GoodsEditType.ADD ? "确定要添加选中商品吗？" : "确定要删除选中商品吗？",
                            new DialogHelper.Callback() {
                                @Override
                                public void onRightClick(AlertDialog alertDialog) {
                                    super.onRightClick(alertDialog);

                                    HashMap<String, Object> params = new HashMap<>();

                                    HashSet<Integer> goodsIds = new HashSet<>();

                                    HashSet<Integer> ids = new HashSet<>();
                                    HashSet<Integer> normalGoodsIds = new HashSet<>();
                                    HashSet<Integer> serviceGoodsIds = new HashSet<>();

                                    selectedGoodsMap.forEach(new BiConsumer<Integer, Goods>() {
                                        @Override
                                        public void accept(Integer integer, Goods goods) {
                                            int goodsId = goods.getGoods_id();
                                            switch (goods.getType()) {
                                                case 1:
                                                    normalGoodsIds.add(goodsId);
                                                    break;
                                                case 2:
                                                case 3:
                                                    serviceGoodsIds.add(goodsId);
                                                    break;
                                            }
                                            ids.add(goods.getId());
                                        }
                                    });
                                    goodsIds.addAll(normalGoodsIds);
                                    goodsIds.addAll(serviceGoodsIds);

                                    BaseObserverImpl<Object> observer = new BaseObserverImpl<Object>(mContext) {
                                        @Override
                                        public void onSuccess() {
                                            super.onSuccess();
                                            getSupportFragmentManager().getFragments().forEach(new Consumer<Fragment>() {
                                                @Override
                                                public void accept(Fragment fragment) {
//                                                    if (fragment instanceof GoodsFragment) {
//                                                        ((GoodsFragment) fragment).afterEdit(goodsIds);
//                                                    }
                                                    reset();
                                                }
                                            });
                                        }
                                    };

                                    if (goodsEditType == GoodsEditType.ADD) {
                                        params.put("goods_ids", normalGoodsIds);
                                        params.put("service_goods_ids", serviceGoodsIds);
                                        requestManager.request(requestManager.mJavaRetrofitService.addGoods(RequestManager.getJsonRequestBody(params)), observer);
                                    } else if (goodsEditType == GoodsEditType.REMOVE) {
                                        params.put("ids", ids);
                                        requestManager.request(requestManager.mJavaRetrofitService.removeGoods(RequestManager.getJsonRequestBody(params)), observer);
                                    }
                                }
                            });
                } else {
                    Toast.makeText(mContext, "请选择商品", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void setCancelOptions() {
        TextView tvOptions = new TextView(mContext);
        tvOptions.setText("取消");
        tvOptions.setTextAppearance(R.style.NormalTextView_Small);
        tvOptions.setTextColor(Color.RED);
        tvOptions.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                reset();
            }
        });
        setOptions(tvOptions);
    }

    private void reset() {
        goodsEditType = GoodsEditType.NORMAL;
        selectedGoodsMap.clear();
        llSelect.setVisibility(View.GONE);
        setManageOptions();
        consumers.forEach(new Consumer<Consumer<GoodsEditType>>() {
            @Override
            public void accept(Consumer<GoodsEditType> goodsEditTypeConsumer) {
                if (goodsEditTypeConsumer != null) {
                    goodsEditTypeConsumer.accept(goodsEditType);
                }
            }
        });
    }

    private void setManageOptions() {
        TextView tvOptions = new TextView(mContext);
        tvOptions.setText("管理商品");
        tvOptions.setTextAppearance(R.style.NormalTextView_Small);
        tvOptions.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int dp10 = SizeUtils.dp2px(10);

                LinearLayout linearLayout = new LinearLayout(mContext);
                linearLayout.setOrientation(LinearLayout.VERTICAL);
                GradientDrawable bg = new GradientDrawable();
                bg.setColor(Color.BLACK);
                bg.setCornerRadius(dp10);
                linearLayout.setBackground(bg);

                PopupWindow popupWindow = new PopupWindow(ScreenUtils.getScreenWidth() / 3, ViewGroup.LayoutParams.WRAP_CONTENT);
                popupWindow.setOutsideTouchable(false);
                popupWindow.setBackgroundDrawable(new ColorDrawable());
                popupWindow.setFocusable(true);
                popupWindow.setOutsideTouchable(true);
                popupWindow.setContentView(linearLayout);
                popupWindow.showAsDropDown(tvOptions, 0, 20, Gravity.RIGHT);

                View.OnClickListener onClickListener = new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        popupWindow.dismiss();
                        llSelect.setVisibility(View.VISIBLE);
                        tvSelectCount.setText("已选择0件商品");
                        GradientDrawable bg = new GradientDrawable();
                        bg.setCornerRadius(360);
                        if (goodsEditType == GoodsEditType.ADD) {
                            tvConfim.setTextColor(Color.WHITE);
                            bg.setColor(ContextCompat.getColor(mContext, R.color.green_theme));
                        } else if (goodsEditType == GoodsEditType.REMOVE) {
                            tvConfim.setTextColor(Color.RED);
                            bg.setColor(Color.parseColor("#FFE9E9"));
                        }
                        tvConfim.setBackground(bg);
                        setCancelOptions();

                        consumers.forEach(new Consumer<Consumer<GoodsEditType>>() {
                            @Override
                            public void accept(Consumer<GoodsEditType> goodsEditTypeConsumer) {
                                if (goodsEditTypeConsumer != null) {
                                    goodsEditTypeConsumer.accept(goodsEditType);
                                }
                            }
                        });
                    }
                };

                TextView tvAdd = new TextView(mContext);
                tvAdd.setGravity(Gravity.CENTER);
                tvAdd.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                tvAdd.setText("添加");
                tvAdd.setTextColor(Color.WHITE);
                tvAdd.setPadding(dp10, dp10, dp10, dp10);
                tvAdd.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        goodsEditType = GoodsEditType.ADD;
                        onClickListener.onClick(v);
                    }
                });
                linearLayout.addView(tvAdd);

                inflater.inflate(R.layout.divider, linearLayout, true);

                TextView tvDelete = new TextView(mContext);
                tvDelete.setGravity(Gravity.CENTER);
                tvDelete.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                tvDelete.setText("删除");
                tvDelete.setTextColor(Color.WHITE);
                tvDelete.setPadding(dp10, dp10, dp10, dp10);
                tvDelete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        goodsEditType = GoodsEditType.REMOVE;
                        onClickListener.onClick(v);
                    }
                });
                linearLayout.addView(tvDelete);
            }
        });

        setOptions(tvOptions);
    }

    @Override
    public void onChecked(Goods goods, boolean checked) {
        if (checked) {
            selectedGoodsMap.put(goods.getGoods_id(), goods);
        } else {
            selectedGoodsMap.remove(goods.getGoods_id());
        }

        tvSelectCount.setText("已选择" + selectedGoodsMap.size() + "件商品");
    }

    @Override
    public void onGoodsEditTypeChange(Consumer<GoodsEditType> goodsEditTypeConsumer) {
        consumers.add(goodsEditTypeConsumer);
    }
}





























